package com.zy.Redis;

//No-SQL的使用：Redis；使用Jedis做缓存
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.Dao.ProvinceDao;
import com.zy.Dao.ProvinceDaoImpl;
import com.zy.Domain.Province;
import com.zy.util.JedisUtils;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService
{
    private ProvinceDao provinceDao=new ProvinceDaoImpl();
    @Override
    public List<Province> searchProvince()
    {
        return provinceDao.searchAll();
    }

    @Override
    public String searchJson()
    {
        Jedis jedisPool = JedisUtils.getJedisPool();
        String province_json = jedisPool.get("province");
        if(province_json==null || province_json.length()==0)
        {
            //缓存中没有，查询数据库
            List<Province> provinces = searchProvince();
            ObjectMapper mapper=new ObjectMapper();
            try
            {
                //JSON序列化
                province_json = mapper.writeValueAsString(provinces);
                //存取数据
                jedisPool.set("province",province_json);
                //归还连接
                jedisPool.close();
            } catch (JsonProcessingException e)
            {
                e.printStackTrace();
            }
        }
        return province_json;
    }
}
